package com.happycat.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.happycat.ResponseModel;
import com.happycat.SysContants;
import com.happycat.config.Audience;
import com.happycat.utils.JwtTokenUtil;



@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
	private Audience audience;
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		ResponseModel<String> responseModel = new ResponseModel<String>();
		responseModel.setCode(SysContants.SYS_SUCCESS_CODE);
		responseModel.setMessage("登录成功！");
		try {
			responseModel.setData(JwtTokenUtil.createJWT(authentication.getPrincipal().toString(), audience));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		response.getOutputStream().write(JSON.toJSONString(responseModel).getBytes());		
	}

}
